package com.parking.bang.rpc.core.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Thread Factory with name definition
 * 
 * @author ivan
 *
 */
public class RPCThreadFactory implements ThreadFactory {

	private static final AtomicInteger threadNum = new AtomicInteger();

	private final AtomicInteger mThreadNum = new AtomicInteger();

	private final String prefix;

	private final boolean daemoThread;

	private final ThreadGroup threadGroup;

	public RPCThreadFactory() {
		this("rpcserver-thread-pool-" + threadNum.getAndIncrement(), false);
	}

	public RPCThreadFactory(String prefix) {
		this(prefix, false);
	}

	public RPCThreadFactory(String prefix, boolean daemo) {
		this.prefix = prefix + "-thread-";
		daemoThread = daemo;
		SecurityManager s = System.getSecurityManager();
		threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
	}

	public Thread newThread(Runnable r) {
		String name = prefix + mThreadNum.getAndIncrement();
		Thread thr = new Thread(threadGroup, r, name, 0);
		thr.setDaemon(daemoThread);
		return thr;
	}

	public ThreadGroup getThreadGroup() {
		return threadGroup;
	}

}
